#include "gd32w51x.h"
#include "stdio.h"
#include "stdint.h"
#include "string.h"
#include "DevicesRF.h"


RFCodeType g_typeRFDecode = {0};


void vRFInit(void)
{
    /* enable the gpio clock */
    rcu_periph_clock_enable(RCU_GPIOB);
    /* enable the CFGCMP clock */
    rcu_periph_clock_enable(RCU_SYSCFG);

    /* configure pin as input */
    gpio_mode_set(GPIOB, GPIO_MODE_INPUT, GPIO_PUPD_PULLUP, GPIO_PIN_7);

    /* enable and set EXTI interrupt to the specified priority */
    nvic_irq_enable(EXTI5_9_IRQn, 0, 0);

    /* connect key EXTI line to GPIO pin */
    syscfg_exti_line_config(EXTI_SOURCE_GPIOB, EXTI_SOURCE_PIN7);

    /* configure EXTI line */
    exti_init(EXTI_7, EXTI_INTERRUPT, EXTI_TRIG_RISING);

    exti_interrupt_flag_clear(EXTI_7);
}

int8_t cRFDecode(RFCodeType *ptypeData, int16_t sValue)
{
    uint8_t ucValue = 0;

    if((sValue > RF_CODE_LOW_MIN) && (sValue < RF_CODE_LOW_MAX))
        ucValue = 0;
    else if((sValue > RF_CODE_HIGH_MIN) && (sValue < RF_CODE_HIGH_MAX))
        ucValue = 1;
    else
        ptypeData->state = necReset;

    ++ptypeData->length;

    switch(ptypeData->state)
    {
        case necReset:
            memset(ptypeData, 0, sizeof(RFCodeType));
            ptypeData->state = necReadUser;
            break;

        case necReadUser:
            ptypeData->user = (ptypeData->user << 1) | ucValue;
            if(ptypeData->length >= 8)
                ptypeData->state = necReadControl;
            break;

        case necReadControl:
            ptypeData->control = (ptypeData->control << 1) | ucValue;
            if(ptypeData->length >= 16)
                ptypeData->state = necReadData;
            break;

        case necReadData:
            if(ptypeData->control == 0x55)
            {
                ptypeData->data = (ptypeData->data << 1) | ucValue;
                if(ptypeData->length >= 32)
                    ptypeData->state = necSucceed;
            }
            else
            {
                /* 低位先发送、先接收 */
                ptypeData->data |= ucValue << (ptypeData->length - 17);
                if(ptypeData->length >= 48)
                    ptypeData->state = necSucceed;
            }
            break;

        default: ptypeData->state = necReadUser; break;
    }

    if(ptypeData->state == necSucceed)
        printf("length: %d, user: %02X, control: %02X, data: %08X\r\n", ptypeData->length, ptypeData->user, ptypeData->control, ptypeData->data);

    return ptypeData->state;
}
